package com.zh.test.Thread;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
/**
 * @Author zh
 * @Description  注解的定时器不支持动态参数,使用手写定时器 https://blog.csdn.net/menghunzhihun/article/details/79993894
 * @Date 2020/9/8
 * @Param
 * @return
 **/
@Component
public class ScheduledHandler implements SchedulingConfigurer {
    // todo 定时器表达式只有6位,定时器时间动态配置 ,表达式上不能超过最大数值,超过按照最大来算,例: 秒最大60,设置120按照60算
    // https://www.cnblogs.com/hanwuxing/p/11288480.html
    // 每小时的 第十分钟43秒 开始 每两分钟执行一次
    String cron = "0/13 * * * * * ";
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(()->{
            System.out.println(new Date());
        },(TriggerContext triggerContext)->{
            return new CronTrigger(cron).nextExecutionTime(triggerContext);
        });
    }
   // @PostConstruct
    public void init(){
        //todo 定时器是单例模式,外部修改定时间隔将影响定时器
        new Thread(()->{
            System.out.println("开启新线程并休眠一分钟后修改定时器时间");
            try {
                Thread.sleep(60*1000);
                cron  = "0/13 * * * * * ";
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();
    }
}
